//
//  SQAppDelegate.m
//  pai
//
//  Created by pro on 14-10-28.
//  Copyright (c) 2014年 linjunjing. All rights reserved.
//

#import "SQAppDelegate.h"
#import "SQUpdateViewController.h"
#import "SQMainViewController.h"
#import "ASIFormDataRequest.h"

@implementation SQAppDelegate

@synthesize navCtrl;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
    SQUpdateViewController* viewCtrl = [SQUpdateViewController alloc];
    self.navCtrl = [[UINavigationController alloc] initWithRootViewController: viewCtrl ];
    self.navCtrl.navigationBar.translucent = NO;
    [self.navCtrl setNavigationBarHidden:YES animated:YES];
    self.window.rootViewController = self.navCtrl;
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
    _asyncSocket = [[AsyncSocket alloc]initWithDelegate:self];
    
    return YES;
}

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    NSLog(@"My token is: %@", deviceToken);
    NSString *pushToken = [[[[deviceToken description]
                             
                             stringByReplacingOccurrencesOfString:@"<" withString:@""]
                            
                            stringByReplacingOccurrencesOfString:@">" withString:@""]
                           
                           stringByReplacingOccurrencesOfString:@" " withString:@""] ;
    
    NSString* url = @"http://cloudchain.co:8080/api/acs_push";
    ASIFormDataRequest* requestFrom = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:url]];
    [requestFrom setPostValue:@"ios" forKey:@"type"];
    [requestFrom setPostValue:pushToken forKey:@"token"];
    [requestFrom startSynchronous];
    NSLog(@"response\n%@",[requestFrom responseString]);
    
}
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
    NSLog(@"Failed to get token, error: %@", error);
}
							
- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    NSLog(@"applicationWillResignActive");
//    dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        if ([Global instance].logined) {
//            on_off_line_t off;
//            off.base.msgtype = 1100;
//            off.base.len = sizeof(on_off_line_t);
//            off.base.error = 0;
//            strcpy(off.username, [[Global instance].userinfo.username UTF8String]);
//            
//            NSMutableData* msgData = [NSMutableData data];
//            [msgData appendBytes:&off length:sizeof(off)];
//            
//            [self sendData:msgData tag:1 withHUD:NO];
//        }
//    });
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    NSLog(@"applicationDidEnterBackground");
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    NSLog(@"applicationWillEnterForeground");

}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    NSLog(@"applicationDidBecomeActive");
    if ([Global instance].logined) {
        on_off_line_t off;
        off.base.msgtype = 1101;
        off.base.len = sizeof(on_off_line_t);
        off.base.error = 0;
        strcpy(off.username, [[Global instance].userinfo.username UTF8String]);
        
        NSMutableData* msgData = [NSMutableData data];
        [msgData appendBytes:&off length:sizeof(off)];
        
        [self sendData:msgData tag:2 withHUD:NO];
    }
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

-(void)sendData:(NSData *)data tag:(NSInteger)tag withHUD:(BOOL)flag
{
    NSLog(@"sendData");
    self.socketData = [NSMutableData dataWithData:data];
    self.socketTag = tag;
    
    NSError* err = nil;
    if (_asyncSocket.isConnected) {
        
        [_asyncSocket readDataWithTimeout:-1 tag:self.socketTag];
        [_asyncSocket writeData:self.socketData withTimeout:-1 tag:self.socketTag];
    }
    else{
        if(![_asyncSocket connectToHost:SOCKETURL onPort:SOCKETPOINT error:&err])
        {
            NSLog(@"Error: %@", err);
        }
    }
}
#pragma AsyncSocket
//建立连接
-(void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    NSLog(@"didConnectToHost");
    [_asyncSocket readDataWithTimeout:-1 tag:self.socketTag];
    [_asyncSocket writeData:self.socketData withTimeout:-1 tag:self.socketTag];
}
//发送数据
-(void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    NSLog(@"didWriteDataWithTag");
    NSLog(@"%@  %ld,",self.socketData,(long)self.socketTag);
    [_asyncSocket readDataWithTimeout:-1 tag:0];
}
//-(void)onSocket:(AsyncSocket *)sock didReadPartialDataOfLength:(NSUInteger)partialLength tag:(long)tag
//{
//    [_asyncSocket readDataToLength:partialLength withTimeout:-1 tag:tag];
//}
//读取数据
-(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSLog(@"didReadData:%ld",tag);
    if (tag == 1) {
        //下线
        
    }
    else if (tag == 2)
    {
        //上线
        acs_base_t base;
        [data getBytes:&base length:sizeof(base)];
        NSLog(@"%d",base.error);
        if (base.error == ACS_SUCCESS) {
            NSLog(@"success");
        }
        else if (base.error == 3070)
        {
            //有消息
            [[NSNotificationCenter  defaultCenter]postNotificationName:@"ACS_ERR_UNREAD_NOTE" object:nil];
        }
    }
    NSLog(@"didReadData");
    //[sock readDataWithTimeout:-1 tag:self.socketTag];
}
//是否加密
-(void)onSocketDidSecure:(AsyncSocket *)sock
{
    NSLog(@"onSocketDidSecure");
}
//遇到错误时关闭连接
-(void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
    NSLog(@"willDisconnectWithError");
    //[[NSNotificationCenter  defaultCenter]postNotificationName:@"socketwillDisconnectWithError" object:nil];
}
//断开连接
-(void)onSocketDidDisconnect:(AsyncSocket *)sock
{
    NSLog(@"onSocketDidDisconnect");
}
@end
